import 'package:bot_toast/bot_toast.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/utils/whl_avatar_utils.dart';
import 'package:cave_flutter/utils/whl_permission_util.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class ComplaintLogic extends GetxController {
  String title = '';

  String categoryId = '';

  /// 业务id
  String objectId = '';

  List<dynamic> reportTypes = [];

  /// 举报类型id
  String selectedTypeId = '';

  String? imagePath;
  TextEditingController contentController = TextEditingController();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    var arguments = Get.arguments;
    if (arguments != null) {
      title = arguments['title'];
      categoryId = arguments['categoryId'] ?? '';
    }

    getCaveAppReportType();
  }

  void getCaveAppReportType() async {
    ResponseData responseData = await WhlApi.getCaveAppReportType.get({}, withLoading: true);
    if (responseData.isSuccess()) {
      // responseData.data;
      // Get.toNamed(Routes.setterPasswordPage, arguments: params);
      reportTypes = responseData.data ?? [];
      update();
    } else {
      MyToast.show(responseData.msg ?? "获取举报类型失败");
    }
  }

  doClickImageAsset() async {
    WhlPermissionUtil.reqStoragePermission(onSuccessAction: () async {
      List<AssetEntity>? resultList = await AssetPicker.pickAssets(Get.context!,
          pickerConfig: const AssetPickerConfig(
            requestType: RequestType.image,
            maxAssets: 1,
          ));
      if (resultList != null && resultList.isNotEmpty) {
        AssetEntity assetEntity = resultList.first;
        imagePath = (await assetEntity.file)?.path;
        update();
      }
    });
  }

  void onConfirm() async {
    if (selectedTypeId.isEmpty) {
      MyToast.show('请选择举报类型');
      return;
    }

    if (contentController.text.isEmpty) {
      MyToast.show('请补充详细的说明');
      return;
    }

    if ((imagePath ?? '').isNotEmpty) {
      BotToast.showLoading();
      AvatarUtils.onGetOssPolicy(imagePath!, onSuccess: (url) {
        BotToast.closeAllLoading();
        if (url.isEmpty) {
          MyToast.show('图片上传失败，请重试');
        } else {
          postReport(url);
        }
      });
    } else {
      postReport('');
    }
  }

  void postReport(String imageUrl) async {
    var params = {
      'typeId': selectedTypeId,
      'categoryId': categoryId,
      'content': contentController.text,
      'imageUrl': imageUrl,
    };

    ResponseData responseData = await WhlApi.caveReport.post(params, withLoading: true);
    if (responseData.isSuccess()) {
      MyToast.show("举报成功");
      Get.back();
    } else {
      MyToast.show(responseData.msg ?? "举报失败");
    }
  }
}
